Ext.namespace('iOS.BaseView');
/*
 * icon 抽象类
 */
Ext.define('BaseIcon', {
    extend     : 'BaseView',
    
    statics    : {
        IconScreen  : 'icon-screen',
    },
    
    _posIn     : {},
    
    _posOut    : {},

    _posCur    : {},
    
    /*
     * 震动图标定时器
     */
    _shakingIcon : null,
    
    /*
     * 图标的动画效果持续时间
     */
    _transitionTime: 450,

    /*
     * 触发shake事件的时间阀值
     */
    _shakeStartTime: 1000,
    
    /*
     * 拖动图标时，图标的缩放度,1为标准大小
     */
    _draggingScale: 1.2,


    /*
     * 改变图标位置时的阀值
     */
    _thresholdPos: {
        x : 20,
        y : 20
    },

    /*
     * 图标震动的角度
     */
    _deg         : 2,
    
    _iconScreen  : null,
    
    /*
     * 图标是否可拖动，默认为true
     */
    _draggable : true,
    /*
     * 图标开始运动的延迟时间
     */
    _transitionDelay: '100ms',
    
    /*
     * 图标的位置状态:in, out, shaking, moving
     */
    _iconState : null,
    
    _eventList : [],

    _dragging : false,
    
    _initDom : function(){
        this.callParent();
        /*
         * "startShake", "stopShake", "initIcon","changePostion"
         * 以上四个事件分别会在IconScreen上和Icon本身上注册
         */
        this._eventList = [
            ['startShake',     this.self.IconScreen],
            ['stopShake',      this.self.IconScreen],
            ['iconIn',         this.self.IconScreen],
            ['iconOut',        this.self.IconScreen],
            ['initIcon',       this.self.IconScreen],
            ['changePosition', this.self.IconScreen],
            ['enableDrag',     this.self.IconScreen],
            ['disableDrag',    this.self.IconScreen],
            ['startShake'],
            ['stopShake'],
            ['initIcon'],
            ['changePosition'],
            ['enableIconClick'],
            ['disableIconClick'],
            ['enableDrag'],
            ['disableDrag']
        ];
    },
    
    _initView  : function(){
        var clsList = [this.self.IconCls,' ',this.self.ViewCls];
        this.getElCache().addClass(clsList.join('')).attr('name', this._name);
        this._iconScreen = iOS.ViewManager.getView(this.self.IconScreen);
        this._iconScreen.addIcon(this._name, this);
        this.setIconImg();
        this.getInPos(this._index);
        this.getOutPos(this._index);
        this.enableIconClick();
        this.iconOut();
        /* disable */
        if(!this._isIframe && !this._app){
            this.getElCache().css('opacity', '0.5');
        }
    },
    
    _attachEventListener: function(){
        this.callParent();
        var that      = this,
            sttc      = this.self,
            startTime, stopTime,
            IconCover = this.getElCacheByCls(sttc.IconCover); 
        this.getElCache().on($.support.touchstart, function(event){
            startTime = new Date();
            IconCover.show();
            that._shakingIcon = setTimeout(function(that){
                IconCover.hide();
                iOS.ViewManager.notify(that.self.IconScreen, 'startShake');
            }, that._shakeStartTime, that);    
        }).on($.support.touchstop  , function(event){
            if(that._enableDrag){
                return;
            }
            stopTime = new Date();
            IconCover.hide();
            if((stopTime - startTime) < that._shakeStartTime){
                clearTimeout(that._shakingIcon);
                that.getElCache().trigger($.support.click);
            } else {
                iOS.ViewManager.notify(that, 'disableIconClick');
            }
        });
        /*this.getElCacheByCls(sttc.ScaleLayer).on('dragover', function(event){
            var $this     = $(this).parent().parent(),
                iconScreen= iOS.ViewManager.getView(that.self.IconScreen),
                dragPos   = iconScreen.draggingIcon.curPos,
                thisTrans = that.getTranslate($this),
                threshold = that._thresholdPos;
            if(Math.abs(dragPos.x - thisTrans.x) >= threshold.x && 
                    Math.abs(dragPos.y - thisTrans.y) <= threshold.y){
                var icons = iconScreen.iconList,
                    curIndex;
                $.each(icons, function(index, value){
                    curIndex = value._index;
                    if(curIndex >= that._index){
                        iOS.ViewManager.notify(value, 'changePosition', [curIndex + 1]);
                    }
                });
            }
        });*/
    },
    
    initIcon: function(){
        this.stopShake();
        this.enableIconClick();
    },

    enableIconClick: function(){
        var that = this,
            sttc = this.self;
        this.getElCache().on($.support.click, function(){
            that.getElCacheByCls(sttc.IconCover).show();
            iOS.ViewManager.notify(sttc.IconScreen, 'iconOut');
            if(that._isIframe){
                iOS.ViewManager.notify(sttc.AppContent, 'runIframe', [that._name, that._src, that._fullScreen, that._topBarColor]);
            } else if(that._app){
                if(iOS.BackStage.checkApp(that._name) && !that._isForce){
                    iOS.ViewManager.notify(sttc.AppContent, 'reAddApp', [that._name]);
                } else {
                    var appCfg = {
                        name   : 'app' + that._name
                    },
                    app    = new that._app(appCfg); 
                }
                iOS.ViewManager.notify(sttc.AppContent, 'runApp', [that._name, that._fullScreen, that._topBarColor]);
            }
        });
    },
    
    /*
     * 在震动icon时，解除icon的单击事件
     */
    disableIconClick: function(){
        this.getElCache().off($.support.click);
    },
    
    _initInnerDom: function(){
        var sttc     = this.self,
            htmlData = [];
        htmlData.push(
            '<div class="',sttc.OperaLayer,'">',
                '<div class="',sttc.ScaleLayer,'">',
                    '<div class="',sttc.ShakeLayer,'">',
                        '<div class="',sttc.IconCover,'"></div>',
                        '<div class="',sttc.IconImg, '" style="',this._getFlex(58),'"></div>',
                        '<div class="',sttc.IconText,'" style="',this._getFlex(12),'">',
                            '<span>',this._text,'</span>',
                        '</div>',
                    '<div>',
                '</div>',
            '</div>'
        );
        this.getElCache().html(htmlData.join(''));
    },
    
    /*
     * icon运动到屏幕内
     */
    iconIn: function(){
        if(this._iconState == 'in'){
            return;
        }
        this._iconScreen.show();
        //涉及到display的显示问题时，会使得duration失效，只好加一个定时器来延缓
        setTimeout(function(that){
            that.getElCache().cssTranslate(that._posIn.x, that._posIn.y);
        }, 1, this);
        this._iconState = true;
        this.getElCacheByCls(this.self.IconCover).hide();
        this._iconState = 'in';
    },
    
    /*
     * icon运动到屏幕外
     */
    iconOut: function(){
        if(this._iconState == 'out'){
            return;
        }
        var that  = this;
        setTimeout(function(that){
            that.getElCache().cssTranslate(that._posOut.x, that._posOut.y);
        }, 1, this);
        this._iconState = 'out';
    },
    
    /*
     * 开始震动图标
     */
    startShake: function(){
        if(this._iconState == 'shaking'){
            return;
        }
        var that      = this,
            icon      = this.getElCacheByCls(this.self.ShakeLayer),
            random    = Math.round(Math.random()) == 0 ? -1 : 1,
            curDeg    = this._deg * random;
        icon[0].style.webkitTransform = 'rotate(' + curDeg + 'deg)';
        icon.on('webkitTransitionEnd', function(){
            curDeg *= -1;
            this.style.webkitTransform = 'rotate(' + curDeg + 'deg)';
        });
        iOS.ViewManager.notify(this.self.HomeButton, 'enableShakeIcon');
        iOS.ViewManager.notify(this, 'enableDrag');
        this._iconState = 'shaking';
    },
    
    /*
     * 结束icon震动
     */
    stopShake  : function(){
        var iconShaker  = this.getElCacheByCls(this.self.ShakeLayer);
        iconShaker.off('webkitTransitionEnd')[0].style.webkitTransform = '';
        iOS.ViewManager.notify(this, 'enableIconClick');
        iOS.ViewManager.notify(this.self.HomeButton, 'enableIconAnim');
        this._iconState = null;
    },

    /*
     * 获取icon屏幕内的位置
     */
    getInPos: function(index){},

    /*
     * 获取icon屏幕外的位置
     */
    getOutPos: function(index){},

    getPosByIndex: function(index){},

    /*
     * 改变图标位置
     */
    changePosition: function(index){
        var pos  = this.getPosByIndex(index),
            icon = this.getElCache(); 
        icon.cssTranslate(pos.x, pos.y);
        this.getInPos(index);
        this.getOutPos(index);
    },

    /*
     * 激活drag
     */
    enableDrag: function(){
        var icon     = this.getElCacheByCls(this.self.OperaLayer),
            that     = this;
        that._enableDrag = true;
        iOS.ViewManager.notify(this, 'disableIconClick');
        icon.on($.support.touchstart, { scope : that}, that.doStart).
             on($.support.touchmove,  { scope : that}, that.doMove).
             on($.support.touchstop,  { scope : that}, that.doEnd);
    },

    /*
     * 关闭drag
     */
    disableDrag: function(){
        var icon       = this.getElCache()[0],
            operaLayer = this.getElCacheByCls(this.self.OperaLayer),
            eventList;
        icon.style.webkitTransitionDelay    = this._transitionDelay + 'ms';
        icon.style.webkitTransitionDuration = this._transitionTime  + 'ms';
        eventList = [$.support.touchstart, ' ', $.support.touchmove, ' ', $.support.touchstop];
        operaLayer.off(eventList.join(''));
        this._enableDrag = false;
    },

    doStart: function(event){
        var that      = event.data.scope || this;
        if(that._dragging){
            return false;
        }
        var icon       = that.getElCache(),
            scaleLayer = that.getElCacheByCls(that.self.ScaleLayer),
            coverLayer = that.getElCacheByCls(that.self.IconCover),
            scale      = that._draggingScale;
        icon.css('z-index', '1');
        coverLayer.show();
        iOS.ViewManager.notify(that, 'stopShake');
        scaleLayer.cssScale(scale);
        icon.css('opacity', '0.8');
        icon[0].style.webkitTransitionDuration = 0;
        icon[0].style.webkitTransitionDelay    = 0;
        that.startPos = {
            x : event.pageX,
            y : event.pageY
        };
        that._iconScreen.draggingIcon = that;
        that._posCur   = that.getTranslate(icon);
        that._dragging = true;
        return false;
    },

    doMove: function(event){
        var that   = event.data.scope || this;
        if(!that._dragging){
            return;
        }
        var icon   = that.getElCache(),
            translate;
        that.curPos = {
            x : that._posCur.x + event.pageX - that.startPos.x,
            y : that._posCur.y + event.pageY - that.startPos.y
        };
        icon.cssTranslate(that.curPos.x, that.curPos.y);
        return false;
    },

    doEnd: function(event){
        var that       = event.data.scope || this,
            icon       = that.getElCache(),
            scaleLayer = that.getElCacheByCls(that.self.ScaleLayer),
            coverLayer = that.getElCacheByCls(that.self.IconCover);
        icon.css('z-index', 'auto');
        coverLayer.hide();
        icon[0].style.webkitTransitionDuration = that._transitionTime;
        icon[0].style.webkitTransitionDelay    = that._transitionDelay;
        icon.css('opacity', '1');
        iOS.ViewManager.notify(that, 'startShake');
        scaleLayer.cssScale(1);
        delete that._iconScreen.draggingIcon;
        that._dragging = false;
        return false;
    },

    _getImgUrl: function(){
        return 'url(resource/images/icons/icon_' + this._name + '.png)';
    },
    
    setIconImg: function(){
        this.getElCacheByCls(this.self.IconImg).
            css('background', this._getImgUrl());
    }
});

iOS.BaseView.BaseIcon = BaseIcon;
